package com.ophiux.common.security.component;

import cn.hutool.core.util.ReUtil;
import com.ophiux.common.core.utils.SpringContextHolder;
import com.ophiux.common.security.annotation.Inner;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @desc: 资源服务器对外直接暴露URL,如果设置contex-path 要特殊处理
 * @author: hhl
 * @date：2023/11/24 10:53
 */
@Slf4j
@ConfigurationProperties(prefix = "security.global.client")
public class PermitAllUrlProperties implements InitializingBean {

	private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

	private static final String[] DEFAULT_IGNORE_URLS = new String[] { "/actuator/**", "/error","/v2/api-docs", "/v3/api-docs","/swagger-ui/**","/swagger-resources/**" };

	@Getter
	@Setter
	private Set<String> ignoreUrls = new HashSet<>();

	@Override
	public void afterPropertiesSet() {
		ignoreUrls.addAll(Arrays.asList(DEFAULT_IGNORE_URLS));
		RequestMappingHandlerMapping mapping = SpringContextHolder.getBean("requestMappingHandlerMapping");
		Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

		map.keySet().forEach(info -> {
			HandlerMethod handlerMethod = map.get(info);

			// 获取方法上边的注解 替代@PathVariable 为 *，如： (/user/info/{username} => /user/info/*)
			Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
			Optional.ofNullable(method)
					.ifPresent(inner -> Objects.requireNonNull(info.getPatternsCondition())
					.getPatterns()
					.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*"))));

			// 获取类上边的注解, 替代@PathVariable 为 *，如： (/user/info/{username} => /user/info/*)
			Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class);
			Optional.ofNullable(controller)
					.ifPresent(inner -> Objects.requireNonNull(info.getPatternsCondition())
					.getPatterns()
					.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, "*"))));
		});
	}

}
